package com.example.snashuitraverl.demos.service.impl;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.snashuitraverl.demos.common.ErrorCode;
import com.example.snashuitraverl.demos.common.SparkManager;
import com.example.snashuitraverl.demos.config.SnowflakeIdWorker;
import com.example.snashuitraverl.demos.domain.Chatai;
import com.example.snashuitraverl.demos.domain.Do.AiDo;
import com.example.snashuitraverl.demos.domain.User;
import com.example.snashuitraverl.demos.exception.BusinessException;
import com.example.snashuitraverl.demos.service.ChataiService;
import com.example.snashuitraverl.demos.mapper.ChataiMapper;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.annotation.Resource;

/**
 * @author 32551
 * @description 针对表【chatai】的数据库操作Service实现
 * @createDate 2024-08-16 12:28:59
 */
@Service
public class ChataiServiceImpl extends ServiceImpl<ChataiMapper, Chatai>
        implements ChataiService {
    @Resource
    private SparkManager sparkManager;

    @Resource
    private UserServiceImpl userServiceimpl;
    @Resource
    private ChataiMapper chataiMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public String useChat(String message, String openId) {
        if (message == null || StringUtils.isBlank(message)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入正确的问题");
        }
        if (openId == null || StringUtils.isBlank(openId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请您登录在使用");
        }
        User user = userServiceimpl.selectOpneId(openId);
        String openID = user.getOpenID();
        if (openID == null || StringUtils.isBlank(openID)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请您登录在使用");
        }
        Chatai chatai = new Chatai();
        CompletableFuture<String> futureResult = CompletableFuture.supplyAsync(() -> {
            String AImessage = sparkManager.sendMesToAIUseXingHuo(message);
//            QueryWrapper<Chatai> chataiQueryWrapper = new QueryWrapper<>();
//            chataiQueryWrapper.eq("openId", openId);
//            Chatai existingChatai = chataiMapper.selectOne(chataiQueryWrapper);
//            if (existingChatai == null) {
//                Integer count = 1;
//                chatai.setSendMessage(message);
//                chatai.setAiMessage(AImessage);
//                chatai.setCount(count);
//                chatai.setOpenId(openId);
//                chataiMapper.insert(chatai);
//                return AImessage;
//            } else {
//                Integer count = existingChatai.getCount();
//                if (count >= 20) {
//                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "您今天的次数已经用完");
//                }
//                LambdaUpdateWrapper<Chatai> updateWrapper = new LambdaUpdateWrapper<Chatai>()
//                        .eq(Chatai::getOpenId, openId)
//                        .set(Chatai::getCount, count + 1)
//                        .set(Chatai::getAiMessage, AImessage)
//                        .set(Chatai::getSendMessage, message);
//                SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
//                long id = idWorker.nextId();
//                String idString = String.valueOf(id);
//                String format = String.format("shen_li%s", idString);
//                redisTemplate.opsForValue().set(format,AImessage,30000, TimeUnit.SECONDS);
//                int update = chataiMapper.update(null, updateWrapper);
//                if (update != 1) {
//                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新失败");
//                }
//                return AImessage;
//            }
            SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
            long id = idWorker.nextId();
            String idString = String.valueOf(id);
            String format = String.format(openID + "%s", idString);
            redisTemplate.opsForValue().set(format, AImessage, 7, TimeUnit.DAYS);
            return AImessage;
        }, threadPoolExecutor);
        try {
            return futureResult.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
    }

    @Override
    public Map<String, String> selectAll() {
//        redisTemplate.opsForValue().get()
        Set<String> keys = redisTemplate.keys("*");
        Map<String, String> redisResult = new HashMap<>();
        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                String keyss = (String) redisTemplate.opsForValue().get(key);
                redisResult.put(key, keyss);
            }
        } else {
            System.out.println("Redis 中没有找到任何 key");
        }

        return redisResult;
    }

    @Override
    public Map<String, String> selectopenId(String openId) {
        User user = userServiceimpl.selectOpneId(openId);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您的openId有误");
        }
        String openIdPrefix = user.getOpenID();
        Set<String> keys = redisTemplate.keys(openIdPrefix + "*");
        HashMap<String, String> stringHashMap = new HashMap<>();
        List<AiDo> aiDoList = new ArrayList<>();
        for (String key : keys) {
            System.out.println(key);
            String RedisVlaue = (String) redisTemplate.opsForValue().get(key);
            stringHashMap.put(key, RedisVlaue);

        }
        if (stringHashMap.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您还未有查询的结果");
        }
        return stringHashMap;

    }

    @Override
    public List<AiDo> selectByList(String openId) {
        User user = userServiceimpl.selectOpneId(openId);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您的openId有误");
        }
        String openIdPrefix = user.getOpenID();
        Set<String> keys = redisTemplate.keys(openIdPrefix + "*");
        AiDo aiDo = new AiDo();
        List<AiDo> aiDoList = new ArrayList<>();
        for (String key : keys) {
            System.out.println(key);
            String RedisVlaue = (String) redisTemplate.opsForValue().get(key);
            aiDo.setKey(key);
            aiDo.setValue(RedisVlaue);
            aiDoList.add(aiDo);
        }
        if (aiDoList.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您还未有查询的结果");
        }
        return aiDoList;

    }

    @Override
    public ResponseBodyEmitter chats(String message) {
        ResponseBodyEmitter responseBodyEmitter = new ResponseBodyEmitter(-1L);
        CompletableFuture.runAsync(() -> {
            try {
                responseBodyEmitter.send(sparkManager.sendMesToAIUseXingHuo(message));
                // 完成发送
                responseBodyEmitter.complete();
            } catch (Exception e) {
                e.printStackTrace();
                // 异常处理
                responseBodyEmitter.completeWithError(e);

            }
        });
        // 返回 ResponseBodyEmitter 对象
        return responseBodyEmitter;
    }


    @Scheduled(cron = "0 0 0 * * ?")
    public void resetDailyCount() {
        UpdateWrapper<Chatai> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("count", 0);
        chataiMapper.update(null, updateWrapper);
    }
}




